<?php
namespace App\Jobs;
use App\Repository\SecKillRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 秒杀活动抢购处理队列
 *
 * @author WangBin
 * @date 2021-10-12
 */
class SecKillRushJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    private $skillId;
    private $qty;
    private $customerId;
    private $productId;
    private $cacheKey = 'sec-kill-activity-'; // 秒杀活动 key
    private $cacheProductStockKey = 'sec-kill-stock-'; // 秒杀商品库存
    private $cacheActiveKey = 'sec-kill-activity-active';

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $skillId, int $qty, int $productId, int $customerId)
    {
        $this->skillId = $skillId;
        $this->qty = $qty;
        $this->customerId = $customerId;
        $this->productId = $productId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 查询缓存库存
        $qty = Cache::get($this->cacheProductStockKey . $this->productId);
        if($qty >= $this->qty) {
            // 扣减 缓存库存
            Cache::decrement($this->cacheProductStockKey . $this->productId, $this->qty);
            $data = ['seckill_id' => $this->skillId, 'qty' => $this->qty, 'customer_id' => $this->customerId];
            SecKillRepository::getInstance()->saveLog($data);
            Log::debug("[队列][秒杀活动] 秒杀成功：客户({$this->customerId}),商品({$this->productId}),秒杀数量({$this->qty}),当前库存({($qty - $this->qty)})");
        } else {
            // 设置缓存秒杀活动结束
            Cache::put($this->cacheActiveKey, 0);
        }
    }
}
